<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\Greeting\Action\Dashboard\Traits;

use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Medium\Contract\MediumContract;
use MoChat\Plugin\Lottery\Contract\LotteryContract;
use MoChat\Plugin\Radar\Contract\RadarContract;

trait MediumTrait
{
    /**
     * @Inject
     * @var MediumContract
     */
    protected $mediumService;

    /**
     * @Inject
     * @var LotteryContract
     */
    protected $lotteryService;

    /**
     * @Inject
     * @var RadarContract
     */
    protected $radarService;

    /**
     * 处理空客户id数据.
     */
    protected function handleMedium(array $mediums): array
    {
        $mediumContent = [];
        foreach ($mediums as $mediumInfo) {
            if ((int) $mediumInfo['type'] === 1) {
                $medium = $this->mediumService->getMediumById($mediumInfo['id'], ['id', 'type', 'content']);
                $greet = empty($medium) ? [] : $this->mediumService->addFullPath(Json::decode($medium['content'], true), $medium['type']);
                $greet['mediumType'] = $medium['type'] ?? 0;
                $greet['type'] = 1;
                $greet['id'] = $mediumInfo['id'];
                $mediumContent[] = $greet;
            } elseif ((int) $mediumInfo['type'] === 2) {
                $lottery = $this->lotteryService->getLotteryById($mediumInfo['id'], ['id', 'name', 'description']);
                $lottery['mediumType'] = 8;
                $lottery['type'] = 2;
                $mediumContent[] = $lottery;
            } elseif ((int) $mediumInfo['type'] === 3) {
                $radar = $this->radarService->getRadarById($mediumInfo['id']);
                $medium['mediumType'] = 8;
                $medium['type'] = 3;
                $medium['id'] = $mediumInfo['id'];
                $medium['imagePath'] = '';
                $medium['imageFullPath'] = '';
                if ($radar['type'] === 1) {
                    $medium['imagePath'] = $radar['linkCover'];
                    $medium['imageFullPath'] = file_full_url($radar['linkCover']);
                }
                if ($radar['type'] === 3) {
                    $article = Json::decode($radar['article']);
                    $medium['imageFullPath'] = file_full_url($article['cover_url']);
                }
                $mediumContent[] = $medium;
            }
        }
        return $mediumContent;
    }
}
